package com.wn.budget.controller;

import com.wn.budget.model.Material;
import com.wn.budget.repository.MaterialRepository;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.UUID;

/**
 * 材料
 */
@RestController
@RequestMapping("Material")
public class MaterialController {

    @Autowired
    private MaterialRepository materialRepository;

    @ApiOperation(value = "根据材料库id，获取材料列表")
    @GetMapping("findAll")
    public Page<Material> findAll(@RequestParam("materialDepotId") String materialDepotId, @RequestParam("pageIndex") int pageIndex, @RequestParam("pageSize") int pageSize) {

        return materialRepository.findByMaterialDepotId(materialDepotId, PageRequest.of(pageIndex, pageSize));
    }

    @PostMapping("insert")
    public boolean insert(HttpServletRequest request, Material project) {
        project.setId(UUID.randomUUID().toString());
        project.setCreateDate(new Date());

        materialRepository.saveAndFlush(project);
        return true;
    }

    @PostMapping("update")
    public boolean update(Material project) {
        materialRepository.saveAndFlush(project);
        return true;
    }

    @GetMapping("findById")
    public Material findById(@RequestParam("id") String id) {
        return materialRepository.findById(id).get();
    }

    @GetMapping("deleteById")
    public void deleteById(@RequestParam("id") String id) {
        materialRepository.deleteById(id);
    }

}
